var express = require('express');
var router = express.Router();
//导入


const moment=require('moment');
const accountModle = require('../../Model/account');

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});


//查看数据
router.get('/bills', function(req, res, next) {
  // let posts=db.get('posts').value();
  accountModle.find().sort({time:-1}).exec((err,data)=>{
    if(err)
    {
      res.status(500).send('出错了');
      return;
    }
     res.render('bills',{posts:data,moment:moment});
  })
 
});


router.get('/bills/create', function(req, res, next) {
  res.render('create');
});



router.post('/bills', function(req, res, next) {
//查看表单数据 
//2023-12-02 => monent =>  new Date()
  //插入数据库
  accountModle.create({
    ...req.body,
    //修改reqbody的值
time:moment(req.body.time).toDate()
  },(err,data)=>{
    if(err)
    {
      res.status(500).send('出错了');
      return;
    }
  res.render('success',{msg:'添加成功',url:'/bills'});
  })
 
  
});

router.get('/bills/:id',(req,res)=>{
  let id=req.params.id;
 accountModle.deleteOne({_id:id},(err,data)=>{
  
  if(err)
  {
    res.status(500).send('出错了');
    return;
  }
   res.render('success',{msg:'删除成功',url:'/bills'});
 });
 
});


module.exports = router;
